﻿using System;
using System.Collections.Generic;
using System.IO;

namespace CSharpHelpers.IOs
{
    public abstract class FileLog
    {
        private static string LogFileName = String.Empty;
        private static string ErrorFileName = String.Empty;
        private static string PrinfFileName = String.Empty;

        private static string VideoDealerLogFileName = String.Empty;
        private static string BaseFileName = String.Empty;
        private static object fileLock = new object();

        public static void SetLogFile(string filename)
        {
            LogFileName = filename;
        }

        public static void SetErrorFile(string filename)
        {
            ErrorFileName = filename;
        }

        public static void SetPrintFile(string filename)
        {
            PrinfFileName = filename;
        }

        public static void LogError(Exception e)
        {
            WriteFile(ErrorFileName, String.Format("Source={1}, Description={2}, Data={3}", DateTime.Now.ToString(), e.Source, e.Message, e.Data.ToString()));
        }

        public static void LogPrint(string description)
        {
            WriteFile(PrinfFileName, description);
        }

        public static void Log(string str)
        {
            WriteFile(LogFileName, str);
        }

        //public static void WriteFile(string filepath, string str)
        //{
        //    if (str != String.Empty)
        //    {
        //        str = "[" + DateTime.Now.ToString() + "]  " + str;
        //    }

        //    FileStream fs = new FileStream(filepath, FileMode.Append);
        //    StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
        //    sw.Flush();
        //    sw.WriteLine(str);
        //    sw.Close();
        //    fs.Close();
        //}

        /// <summary>
        ///写临时文件
        /// </summary>
        /// <param name="buffer"></param>
        public static void WriteBakFile(string filepath, string str)
        {
            FileStream fs = new FileStream(filepath, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
            sw.Flush();
            sw.WriteLine(str);

            sw.Close();
            fs.Close();
        }

        /// <summary>
        /// 纯读文件方法,把文件加载到内存中
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ReadFile(string filePath)
        {
            byte[] buffer;
            FileStream fileStream = null;
            try
            {
                fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                int length = (int)fileStream.Length;  // get file length
                buffer = new byte[length];            // create buffer
                int count;                            // actual number of bytes read
                int sum = 0;                          // total number of bytes read                 // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                {
                    sum += count;  // sum is a buffer offset for next reading
                }
            }
            catch (Exception ex)
            {
                buffer = new byte[] { };
                LogError(ex);
            }
            finally
            {
                if (fileStream != null)
                    fileStream.Close();
            }
            string sbuf = string.Empty;
            for (int i = 0; i < buffer.Length; i++)
            {
                sbuf += Convert.ToChar(buffer[i]);
            } return sbuf;
        }

        /// <summary>
        /// 删除临时文件
        /// </summary>
        /// <param name="filePath"></param>
        public static void DeleteFile(string filePath)
        {
            File.Delete(filePath);
        }

        public static void SetBaseFile(string filename)
        {
            BaseFileName = filename;
        }

        public static void SetVideoDealerLogFileName(string filename)
        {
            VideoDealerLogFileName = filename;
        }

        public static void LogError(Exception e, string command = "")
        {
            WriteFile(ErrorFileName,
                command +
                String.Format("Source={1}, Description={2}, Data={3}", DateTime.Now.ToString(), e.Source, e.Message,
                    e.Data.ToString()));
        }

        public static void LogFlashError(string strError)
        {
            WriteFile(ErrorFileName, strError);
        }

        public static void LogVideoDealer(string str)
        {
            WriteFile(VideoDealerLogFileName, str);
        }

        public static void LogBase(string str)
        {
            WriteFile(BaseFileName, str);
        }

        public static void LogByCommunicationAndCommad(string commad, List<string> megs)
        {
            string str = "send:" + commad + " ;";

            foreach (string strValue in megs)
            {
                str += "{" + strValue + "}";
            }

            str = str.Replace(",-1", "");

            WriteFile(LogFileName, str);
        }

        public static void LogByCommunication(List<string> megs)
        {
            string str = string.Empty;

            foreach (string strValue in megs)
            {
                str += "{" + strValue + "}";
            }

            str = str.Replace(",-1", "");

            WriteFile(LogFileName, str);
        }

        public static void WriteFile(string filepath, string str)
        {
            lock (fileLock)
            {
                if (str != String.Empty)
                {
                    str = "[" + DateTime.Now.ToString() + "]  " + str;
                }

                filepath = filepath + DateTime.Now.ToString("yyyy-MM-dd") + ".log";

                try
                {
                    FileStream fs = new FileStream(filepath, FileMode.Append, FileAccess.Write);
                    using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default))
                    {
                        sw.WriteLine(str);
                        sw.Flush();
                        sw.Close();
                        fs.Close();
                    }
                }
                catch (IOException e)
                {

                }
            }
        }

        public static void CreateFolder(string filepath)
        {
            if (!Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);
            }
        }
    }
}
